﻿using System;
using System.Collections.Generic;

namespace StockModel
{
	public static class QuotationCollectionFiller
	{
		public static IList<Quotation> CreateOneSecondSpacedCollection(Quotation from, Quotation to, ExchangeMarket market)
		{
			List<Quotation> result = new List<Quotation>();

			decimal secondsDifference = (decimal)Math.Round((to.Date - from.Date).TotalSeconds);
			bool differentQuoteTypes = from.Type != to.Type; // Check to improve performance, we check once and if it does not change we don't check anymore

			Quotation lastQuotationProcessed = from;
			for (int index = 0; index < Math.Round(secondsDifference); index++)
			{
				if (secondsDifference - index <= 1)
				{
					lastQuotationProcessed = QuotationCollectionFiller.ProcessLastQuotation(to, lastQuotationProcessed);
				}
				else
				{
					lastQuotationProcessed = QuotationCollectionFiller.ProcessQuotation(lastQuotationProcessed, differentQuoteTypes, market);
				}

				result.Add(lastQuotationProcessed);
			}

			return result;
		}

		private static Quotation ProcessQuotation(Quotation lastQuotationProcessed, bool differentQuoteTypes, ExchangeMarket market)
		{
			DateTime nextQuotationDate = lastQuotationProcessed.Date + new TimeSpan(0, 0, 1);

			if (!differentQuoteTypes || lastQuotationProcessed.Type == market.GetQuoteType(nextQuotationDate))
			{
				lastQuotationProcessed = lastQuotationProcessed.ShallowCopy();
				lastQuotationProcessed.Date = nextQuotationDate;
			}
			else
			{
				lastQuotationProcessed = (Quotation)lastQuotationProcessed.Clone();
				lastQuotationProcessed.Date = nextQuotationDate;
				lastQuotationProcessed.Type = market.GetQuoteType(nextQuotationDate);
			}

			return lastQuotationProcessed;
		}

		private static Quotation ProcessLastQuotation(Quotation quotationToProcess, Quotation lastQuotationProcessed)
		{
			Quotation result;

			if (lastQuotationProcessed.Equals(quotationToProcess))
			{
				Quotation tempQuotation = lastQuotationProcessed.ShallowCopy(); // Don't save a new quotation with the same values, create a shallow copy to save memory
				tempQuotation.Date = quotationToProcess.Date;
				tempQuotation.Acquisition = quotationToProcess.Acquisition;
				result = tempQuotation;
			}
			else
			{
				// As we are saving as a new Quotation when the Type changes to store the Closed quotation (among others) we need to change the Acquisition time if it is the same as the previous one
				if (lastQuotationProcessed.Type != quotationToProcess.Type && lastQuotationProcessed.Acquisition == quotationToProcess.Acquisition)
				{
					quotationToProcess.Acquisition = quotationToProcess.Date;
				}
				result = quotationToProcess;
			}

			return result;
		}
	}
}
